const express = require('express');
const http = require('http');
const { Server } = require('socket.io');

const app = express();
const server = http.createServer(app);
const io = new Server(server, {
  cors: {
    origin: "*",
    methods: ["GET", "POST"]
  }
});

// 内存存储（生产环境建议使用数据库）
let users = new Map();  // 存储用户信息
let chatHistory = [];   // 聊天记录

// WebSocket 连接处理
io.on('connection', (socket) => {
  console.log('New client connected:', socket.id);

  // 用户加入
  const userId = generateUserId();
  users.set(userId, {
    id: userId,
    socket,
    joinedAt: new Date()
  });

  // 发送加入通知
  io.emit('userJoined', {
    userId,
    username: `User ${userId.slice(0,5)}`
  });

  // 消息处理
  socket.on('sendMessage', (message) => {
    const currentUser = users.get(userId);
    
    // 构建消息对象
    const msg = {
      userId,
      username: currentUser.username,
      text: message,
      timestamp: new Date()
    };

    // 广播消息给所有客户端
    io.emit('newMessage', msg);
    
    // 存储聊天记录（可选）
    chatHistory.push(msg);
  });

  // 用户离开
  socket.on('disconnect', () => {
    console.log('Client disconnected:', socket.id);
    if (users.has(userId)) {
      users.delete(userId);
      io.emit('userLeft', userId);
    }
  });
});

// 生成唯一用户ID
function generateUserId() {
  return Math.random().toString(36).substr(2, 9);
}

// 静态文件服务
app.use(express.static('public'));

// 启动服务器
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});